<template>
    <LoginBase title="账号注册">
        <a-form ref="formRef" :model="registerRequest" :rules="registerFormRules">
            <a-form-item name="name" has-feedback>
                <a-input v-model:value="registerRequest.name" size="large" placeholder="用户名" />
            </a-form-item>
            <a-form-item name="password" has-feedback>
                <a-input-password v-model:value="registerRequest.password" size="large" placeholder="输入密码" />
            </a-form-item>
            <a-form-item name="email" has-feedback>
                <a-input v-model:value="registerRequest.email" size="large" placeholder="邮箱" />
            </a-form-item>
            <a-form-item name="tel" has-feedback>
                <a-input size="large" v-model:value="registerRequest.tel" placeholder="手机号" />
            </a-form-item>
            <a-form-item name="mobileCode">
                <a-input-search v-model:value="registerRequest.mobileCode" size="large" placeholder="验证码"
                    @search="onSendMobileCode">
                    <template #enterButton>
                        <a-button :disabled="sendMobileCodeState">{{ sendMobileCodeBtnText }}</a-button>
                    </template>
                </a-input-search>
            </a-form-item>
            <a-form-item>
                <a-input v-model:value="registerRequest.QQ" size="large" placeholder="QQ/选填" />
            </a-form-item>
            <a-form-item>
                <a-input v-model:value="registerRequest.wechat" size="large" placeholder="微信号/选填" />
            </a-form-item>
            <a-form-item>
                <a-textarea v-model:value="registerRequest.address" size="large" placeholder="地址/选填" />
            </a-form-item>
            <a-form-item>
                <a-button size="large" block type="primary" @click="onRegister">注册</a-button>
            </a-form-item>
            <a-form-item>
                <div style="text-align: right;">
                    <router-link to="/user/login">已有账号,前往登录</router-link>
                </div>
            </a-form-item>
        </a-form>
    </LoginBase>
</template>
<script lang="ts" setup>
import { ref, withDefaults, defineProps } from "vue";
import LoginBase from "./LoginBase.vue";
import { UserService } from "@/services/User/UserService";
import { UserDto } from "@/models/User/UserDto";
import { UserContext } from "@/utils/UserContext";
import { useRouter } from 'vue-router'
import { message, Modal } from 'ant-design-vue';
import { Convert } from "@/utils/Convert";
import { RuleObject } from "ant-design-vue/lib/form/interface";
import { UIForm } from "@/utils/UIForm";
import { Regular, Regex } from "@/utils/Regular";

const registerRequest = ref<UserDto.RegisterRequest>(new UserDto.RegisterRequest());
const loading = ref(false);
const $router = useRouter();
const formRef = ref()

/** 获取url地址中的参数 */
const props = withDefaults(defineProps<{ shareId: string }>(), { shareId: "" });
const shareId = Convert.toNumber(props.shareId);

//验证用户名是否占用
let validatorName = async (rule: RuleObject, value: string) => {
    if (!/^[a-z0-9]{3,20}$/i.test(value)) {
        return Promise.resolve("用户只能由3-20位英文和数字组成");
    }
    if (await validatorField("Name", value)) {
        return Promise.reject("该用户名已被注册");
    }
}

const sendMobileCodeState = ref(true);

//验证手机号是否占用
let validatorTel = async (rule: RuleObject, value: string) => {

    if (!/^\d{11}$/.test(value)) {
        sendMobileCodeState.value = true;
        return Promise.reject("手机号错误");
    }

    if (await validatorField("Tel", value)) {
        sendMobileCodeState.value = true;
        return Promise.reject("手机号已被注册");
    }

    sendMobileCodeState.value = false;
}

//验证邮箱号是否占用
let validatorEmail = async (rule: RuleObject, value: string) => {

    if (!Regular.buildRegExp(Regex.Email).test(value)) {
        return Promise.reject("邮箱格式错误");
    }

    if (await validatorField("Email", value)) {
        return Promise.reject("邮箱已被注册");
    }
}

const registerFormRules = ref({
    name: [{
        required: true, validator: validatorName, trigger: 'blur'
    }],
    password: [{ required: true, message: '密码必填' },
    {
        pattern: /^[a-z0-9]{3,20}$/i, message: "密码只能由3-20位英文和数字组成"
    }],
    tel: [{
        required: true, validator: validatorTel, trigger: 'blur'
    }],
    email: [{
        required: true, validator: validatorEmail, trigger: 'blur'
    }],
    mobileCode: [{
        required: true, message: '手机验证码必填'
    }]
});





/**服务器验证字段 */
const validatorField = async (type: string, value: string) => {
    // var rs = await UserService.registerValidate({
    //     type: type,
    //     value: value
    // })
    // return rs.Code != 0;
    return true;
}



const sendMobileCodeBtnText = ref("发送验证码");
//发送手机验证码
const onSendMobileCode = async () => {

    if (registerRequest.value.tel == "") {
        message.error("请输入手机号");
        return;
    }

    //let rs = await AuthCodeService.sendRegisterAutoCode(registerRequest.value.tel);

    // if (rs.Code > 0) {
    //     message.error(rs.Msg);
    //     return;
    // }

    sendMobileCodeState.value = true;
    let step = 60;
    let stepTime = setInterval(function () {
        step = step - 1;
        sendMobileCodeBtnText.value = `(${step})秒后重发`;
        if (step <= 0) {
            sendMobileCodeBtnText.value = "发送验证码"
            sendMobileCodeState.value = false;
            clearInterval(stepTime);
        }
    }, 1000)
}


//注册
const onRegister = async () => {
    loading.value = true;
    if (!await UIForm.Validate(formRef)) {
        return;
    }
    registerRequest.value.agentId = shareId;
    let rs = await UserService.registerAsync(registerRequest.value);
    if (rs.code == 0) {
        UserContext.add(
            rs.data.Name,
            rs.data.Token,
            rs.data.User_Id
        );
        loading.value = false;

        Modal.success({
            title: "提示",
            content: " 恭喜你注册成功,你拥有3天体验时间",
            onOk: () => {
                $router.push("/");
            },
            okText: "体验一下"
        })

    } else {
        message.error(rs.msg);
    }
}

</script>
